package com.ql.dev.customwebview.library.views;

import android.util.Log;
import android.webkit.WebView;

import java.lang.ref.WeakReference;

/**
 * 可以调用Js的方法
 * Created by Quanguanzhou on  2017/4/10 0010.
 * Copyright (c) 2015, quanguanzhou83@gmail.com All Rights Reserved.
 */
public class JsCallback {
    /**
     * Js中定义好的方法与固定参数
     */
    private static final String CALLBACK_JS_FORMAT = "javascript:%s.callback(%d, %d %s);";
    private int mIndex;
    private boolean mCouldGoOn;
    /**
     * 弱引用WebView，方便GC回收
     */
    private WeakReference<WebView> mWebViewRef;
    private int mIsPermanent;
    private String mInjectedName;

    public JsCallback (WebView view, String injectedName, int index) {
        mCouldGoOn = true;
        mWebViewRef = new WeakReference<WebView>(view);
        mInjectedName = injectedName;
        mIndex = index;
    }

    /**
     * 前面两个判断不可去掉，每个方法都需要判断
     * @param args
     * @throws JsCallbackException 抛出异常
     */
    public void apply (Object... args) throws JsCallbackException {
        if (mWebViewRef.get() == null) { // 判断WebView是否还存在
            throw new JsCallbackException("the WebView related to the JsCallback has been recycled");
        }
        if (!mCouldGoOn) { // 一次的点击不能被调用一次以上
            throw new JsCallbackException("the JsCallback isn't permanent,cannot be called more than once");
        }
        StringBuilder sb = new StringBuilder();
        for (Object arg : args){
            sb.append(",");
            boolean isStrArg = arg instanceof String;
            if (isStrArg) {
                sb.append("\"");
            }
            sb.append(String.valueOf(arg));
            if (isStrArg) {
                sb.append("\"");
            }
        }
        String execJs = String.format(CALLBACK_JS_FORMAT, mInjectedName, mIndex, mIsPermanent, sb.toString());
        Log.d("JsCallBack", execJs);
        mWebViewRef.get().loadUrl(execJs);
        mCouldGoOn = mIsPermanent > 0;
    }

    /**
     *
     * @param value
     */
    public void setPermanent (boolean value) {
        mIsPermanent = value ? 1 : 0;
    }

    public static class JsCallbackException extends Exception {
        public JsCallbackException (String msg) {
            super(msg);
        }
    }
}
